/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.bigstorage.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.bigstorage.entity.Goods;
import com.jeesite.modules.bigstorage.dao.GoodsDao;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.bigstorage.entity.GoodsSpec;
import com.jeesite.modules.bigstorage.dao.GoodsSpecDao;

/**
 * 商品表Service
 * @author zhuqingya
 * @version 2019-12-13
 */
@Service
@Transactional(readOnly=true)
public class GoodsService extends CrudService<GoodsDao, Goods> {
	
	@Autowired
	private GoodsSpecDao goodsSpecDao;
	
	/**
	 * 获取单条数据
	 * @param goods
	 * @return
	 */
	@Override
	public Goods get(Goods goods) {
		Goods entity = super.get(goods);
		if (entity != null){
			GoodsSpec goodsSpec = new GoodsSpec(entity);
			goodsSpec.setStatus(GoodsSpec.STATUS_NORMAL);
			entity.setGoodsSpecList(goodsSpecDao.findList(goodsSpec));
		}
		return entity;
	}
	
	/**
	 * 查询分页数据
	 * @param goods 查询条件
	 * @param goods.page 分页对象
	 * @return
	 */
	@Override
	public Page<Goods> findPage(Goods goods) {
		return super.findPage(goods);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param goods
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Goods goods) {
		super.save(goods);
		// 保存上传图片
		FileUploadUtils.saveFileUpload(goods.getId(), "goods_image");
		// 保存 Goods子表
		for (GoodsSpec goodsSpec : goods.getGoodsSpecList()){
			if (!GoodsSpec.STATUS_DELETE.equals(goodsSpec.getStatus())){
				goodsSpec.setGoodsId(goods);
				if (goodsSpec.getIsNewRecord()){
					goodsSpecDao.insert(goodsSpec);
				}else{
					goodsSpecDao.update(goodsSpec);
				}
			}else{
				goodsSpecDao.delete(goodsSpec);
			}
		}
	}
	
	/**
	 * 更新状态
	 * @param goods
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Goods goods) {
		super.updateStatus(goods);
	}
	
	/**
	 * 删除数据
	 * @param goods
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Goods goods) {
		super.delete(goods);
		GoodsSpec goodsSpec = new GoodsSpec();
		goodsSpec.setGoodsId(goods);
		goodsSpecDao.deleteByEntity(goodsSpec);
	}
	
}